﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BCGPSRESTful.WebApiConfig
{
    /// <summary>
    /// 
    /// </summary>
    public class RequireModelValidateAttribute:ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
                return;

            //foreach (var item in context .ModelState)
            //{
            //    if(item.Value.ValidationState!=Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
            //    {
            //        continue;
            //    }
            //}

            //base.OnActionExecuting(context);


            ErrorMessageDto errorMessageDto = new ErrorMessageDto
            {
                ErrorCode = "999999997"
            };

            foreach (var item in context.ModelState)
            {
                if (item.Value.ValidationState != ModelValidationState.Invalid)
                {
                    continue;
                }

                string[] errors = item.Value.Errors.Select(p => p.ErrorMessage).ToArray();

                if (string.IsNullOrWhiteSpace(errorMessageDto.ErrorMessage))
                {
                    errorMessageDto.ErrorMessage = errors.FirstOrDefault();
                }

                //errorMessageDto.ErrorDetails.Add(StringUtils.ToSnakeCase(item.Key), errors);
            }

            context.Result = new ObjectResult(errorMessageDto)
            {
                StatusCode = 400
            };
        } 
    }
}
